package repository

import (
	"ShortLink/Core/LogHelper"
	mysql "ShortLink/Core/Mysql"
	entity "ShortLink/Data/Entity"
	"time"
)

// 添加
func Add(link *entity.LinkInfo) bool {
	r := mysql.WriteDB.Create(&link)
	if r.RowsAffected == 0 || r.Error != nil {
		log := new(LogHelper.ErrorLog)
		log.Title = "增加数据失败"
		log.Result = r
		log.Data = link
		LogHelper.Error(log)
		return false
	}
	return true
}

// 删除
func Delete(segment string) int64 {
	var link entity.LinkInfo
	sql := "segment=?"
	r := mysql.WriteDB.Delete(&link, sql, segment)
	if r.RowsAffected == 0 || r.Error != nil {
		log := new(LogHelper.ErrorLog)
		log.Title = "删除数据异常"
		log.Result = r
		log.Data = segment
		LogHelper.Warn(log)
	}
	return r.RowsAffected
}

// 查询
func QueryBySegment(segment string) *entity.LinkInfo {
	sql := "segment=?"
	data := new(entity.LinkInfo)
	mysql.ReadDB.First(&data, sql, segment)
	return data
}

// 延期
func Extension(segment string, expiry_time time.Time) {
	sql := "update link_info set expiry_time=? where segment=?"
	var r = mysql.WriteDB.Exec(sql, expiry_time, segment)
	if r.Error != nil {
		LogHelper.Error(r.Error)
	}
}

// 修改跳转地址
func EditJumpLink(segment string, jumpLink string) int64 {
	sql := "update link_info set jump_link=? where segment=?"
	var r = mysql.WriteDB.Exec(sql, jumpLink, segment)
	if r.Error != nil {
		LogHelper.Error(r.Error)
	}
	return r.RowsAffected
}
